﻿using System;
using Cav;
using Cav.WinForm.BaseClases;
using Nefela.BusinessLogic;
using Nefela.CommonTypes;

namespace Nefela.UI
{
    public partial class fmFCCAddEdit : DialogFormBase
    {
        public fmFCCAddEdit()
        {
            InitializeComponent();
        }

        public FieldCardCustomerType FieldItemRow { get; set; }
        public FieldCardCustomerType originalFRRow { get; set; }

        private void fmRIAddEdit_Load(object sender, System.EventArgs e)
        {
            if (FieldItemRow == null)
                FieldItemRow = new FieldCardCustomerType();
            else
                originalFRRow = FieldItemRow.Clone();

            this.tbDescription.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.FieldItemRow, "Name", true));
            this.tbLabelText.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.FieldItemRow, "LabelText", true));
            this.cbUserInput.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.FieldItemRow, "UserInput", true));

            setBL = (SettingsBL)this.BusinessLogic;

        }

        SettingsBL setBL;

        private void fmRIAddEdit_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (this.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                if (originalFRRow != null)
                {
                    FieldItemRow.Name = originalFRRow.Name;
                    FieldItemRow.LabelText = originalFRRow.LabelText;
                    FieldItemRow.UserInput = originalFRRow.UserInput;
                }

                return;
            }

            if (!setBL.ModelPackegeDocs.CardCustomer.Contains(this.FieldItemRow))
            {
                String msg = setBL.ModelPackegeDocs.AddFieldCardCustomer(this.FieldItemRow);
                if (!msg.IsNullOrWhiteSpace())
                {
                    Dialogs.InformationF(this, msg);
                    e.Cancel = true;
                    return;
                }
            }

            // TODO вынести код в класс полей (сделать метод проверки)
            foreach (var item in setBL.ModelPackegeDocs.CardCustomer)
            {
                if (item == FieldItemRow)
                    continue;

                if (item.Name == FieldItemRow.Name)
                {
                    Dialogs.InformationF(this, "Поле с таким именем уже есть");
                    e.Cancel = true;
                    return;
                }

                if (item.LabelText == FieldItemRow.LabelText)
                {
                    Dialogs.InformationF(this, "Поле с такой меткой уже есть");
                    e.Cancel = true;
                    return;
                }


            }
        }
    }
}
